package com.test20.customer;

import java.util.LinkedList;

/**
 * 使用java实现生产者消费者模型
 * @author wangquan
 *
 */
public class CustomerDemo {
	private LinkedList<Integer> linkedList = new LinkedList<>();
	private int i = 0;
	private int max = 5;
	public static void main(String[] args) {
		new CustomerDemo().start();
	}
	
	public void start(){
		new Customer().start();
		new Product().start();
	}
	class Customer extends Thread {
		@Override
		public void run() {
			while (true) {
				synchronized (linkedList) {
					try {
						//如果是空的，就把自己wait，等待生产者唤醒
						if (linkedList.isEmpty()) {
							linkedList.wait();
						}
						System.out.println(linkedList.getLast());
						linkedList.removeLast();
						linkedList.notify();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	class Product extends Thread {
		@Override
		public void run() {
			while (true) {
				synchronized (linkedList) {
					try {
						if (linkedList.size()>=max) {
							linkedList.wait();
						}
						linkedList.push(i++);
						Thread.sleep(1000);
						linkedList.notify();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
